package com.jn.mvvm2.viewmodel;

import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStoreOwner;

import com.jn.mvvm2.entity.Pet;
import com.jn.mvvm2.repository.PetRepository;

import java.util.List;

public class PetViewModel extends AndroidViewModel {
    private final PetRepository petRepository;
    private final MutableLiveData<List<Pet>> petListLiveData;

    public PetViewModel(@NonNull Application application) {
        super(application);
        petRepository = new PetRepository();
        petListLiveData = new MutableLiveData<>();
    }

    public LiveData<List<Pet>> getPetList() {
        loadPetList();
        return petListLiveData;
    }

    private void loadPetList() {
        // 模拟网络请求，实际开发中应替换为真实的网络请求
        petListLiveData.setValue(petRepository.getPetList());
    }

    public void searchPets(String query) {
        // 模拟搜索，实际开发中应替换为真实的搜索逻辑
        List<Pet> filteredList = petRepository.searchPets(query);
        petListLiveData.setValue(filteredList);
    }

    public static class Factory extends ViewModelProvider.NewInstanceFactory {
        @NonNull
        private final Application application;

        public Factory(@NonNull Application application) {
            this.application = application;
        }

        @Override
        public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
            if (modelClass.isAssignableFrom(PetViewModel.class)) {
                //noinspection unchecked
                return (T) new PetViewModel(application);
            }
            throw new IllegalArgumentException("Unknown ViewModel class");
        }
    }
}